import { message } from 'antd'
import _ from 'underscore'
import { handleReq_headers } from './lib/header'
import { handleDescription } from './lib/description'
import { handleRequestUrl } from './lib/path'
import { handleResponses } from './lib/response'
import { handleReqBodyType, handleReq_body_form, isContentTypeJson } from './lib/body'
import { handleReqParams, handleReq_query } from './lib/param'
import SnowflakeId from 'snowflake-id';

const snowflake = new SnowflakeId();


const filterItemAndFolder = (item, pItem, result) => {
  if (item.hasOwnProperty('request')) {// 子选项
    item.catname = pItem.name
    item.catid = pItem.id
    result.requests.push(item)
  } else {// 文件夹
    item.parent_id = pItem.id
    item.id = getVid()
    item.desc = item.description
    result.folders.push(item)
    pItem.children = pItem.children ? pItem.children : []
    pItem.children.push(item)
    if (item.item && item.item.length > 0) {
      item.item.forEach(it => {
        filterItemAndFolder(it, item, result)
      })
    }
  }
}

/**
 * keys：
 *      'title',
 *      'path',
 *      'catname',
 *      'method',
 *      'desc',
 *
 *      'req_query',
 *      'req_params',
 *      'req_headers',
 *      'req_body_type',
 *      'req_body_form',
 *      'req_body_other',
 *      'req_body_is_json_schema'
 *
 *      'res_body_type'
 *      'res_body_is_json_schema'
 *      'res_body'
 */
const importPostman = (data) => {
  try {
    const { name, request, response, catname, catid } = data
    /**
     * header：one of Header List | string
     */
    const { url, method, header, body, description } = request

    /**
     * mode：enum of {raw、urlencoded、formdata、file、graphql}
     */

    let res = {}

    res.title = name

    res.path = handleRequestUrl(url, header)

    res.url = _.isString(url) ? url : url.raw

    // 所属分类名
    res.catname = catname

    res.catid = catid

    res.method = method

    res.desc = handleDescription(description)

    res.req_query = _.isString(url) ? [] : handleReq_query(url.query)

    res.req_params = handleReqParams(res.path)

    res.req_headers = _.isString(header) ? [] : handleReq_headers(header)

    res.req_body_type = handleReqBodyType(body, header)

    res.req_body_form = handleReq_body_form(body)

    res.req_body_is_json_schema = isContentTypeJson(header)

    // response
    res = Object.assign({}, res, handleResponses(response))

    return res
  } catch (err) {
    message.error(`${err.message}, 导入的postman格式有误`)
    console.error(`${err.message}, 导入的postman格式有误`, err)
  }
}

const getVid = () => {
  return "vid:" + snowflake.generate();
}

function postman(importDataModule) {
  function run(res, options) {
    try {
      res = JSON.parse(res)
      let interfaceData = { apis: [], cats: [], treeCats:[], isTreeCat: true}
      const info = res.info;

      const rootId = getVid();
      const rootItem = {
        name: info.name,
        desc: info.name,
        parent_id: options.selectCatid,
        id: rootId,
        children: []
      }

      interfaceData.cats.push(rootItem)
      interfaceData.treeCats.push(rootItem)

      const result = {
        folders: [],
        requests: []
      }

      res.item.forEach(item => {
        filterItemAndFolder(item, rootItem, result)
      })

      // 筛选接口和分类
      let { folders, requests } = result

      // 分类数据
      if (folders && Array.isArray(folders)) {
        folders.forEach((tag) => {
          interfaceData.cats.push({
            name: tag.name,
            desc: tag.description,
            parent_id: tag.parent_id
          })
        })
      }

      // 转换为需要的接口数据格式
      if (requests && requests.length) {
        for (let key in requests) {
          let data = importPostman(requests[key])
          interfaceData.apis.push(data)
        }
      }

      return interfaceData
    } catch (e) {
      message.error('文件格式必须为JSON')
    }
  }

  if (!importDataModule || typeof importDataModule !== 'object') {
    console.error('obj参数必需是一个对象')
    return null
  }

  importDataModule.Postman2 = {
    name: 'Postman2',
    run: run,
    desc: 'Postman数据导入（支持 v2.0+）'
  }
}

module.exports = function () {
  this.bindHook('import_data', postman)
}
